package com.atguigu.day03;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction;

//并行数据源发送
public class Example8 {
    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

//        env
//                .addSource(new ParaIntSource()).setParallelism(2) //并行子任务为2
//                .print().setParallelism(2); //每个并行子任务都执行一次run


        env
                .addSource(new ParaIntSource()).setParallelism(2)
                .rescale() //如果下游算子的并行子任务是上游的整数倍的时候，那么上游算子会将数据发送给下游的某几个子任务
                .print("rescale: ").setParallelism(4);

        env
                .addSource(new ParaIntSource()).setParallelism(2)
                .rebalance() //随机平均发到下游每个插槽
                .print("rebalance: ").setParallelism(4);




        env.execute();
    }

    //实现并行数据源
    public static class ParaIntSource extends RichParallelSourceFunction<Integer>{
        @Override
        public void open(Configuration parameters) throws Exception {
            super.open(parameters);
            System.out.println("并行子任务的索引是："+ getRuntimeContext().getIndexOfThisSubtask() +",生命周期开始");
        }

        @Override
        public void close() throws Exception {
            super.close();
            System.out.println("并行子任务的索引是："+ getRuntimeContext().getIndexOfThisSubtask() +",生命周期结束");
        }

        @Override
        public void run(SourceContext<Integer> ctx) throws Exception {

            for (int i = 1; i < 9; i++) {
                //并行子任务的索引底层是0和1，当索引为0时，那么会将偶数发送下去;打印是1和2(也就是偶数打印到1插槽 奇数打印到2插槽)
                if (i%2 == getRuntimeContext().getIndexOfThisSubtask())
                ctx.collect(i);
            }
        }

        @Override
        public void cancel() {

        }
    }

}
